package com.wzvtc.vsl.securitytool.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.TextUtils;

import com.wzvtc.vsl.securitytool.R;
import com.wzvtc.vsl.securitytool.service.GPSService;

/**
 * Created by Vsl on 2015/3/25.
 */
public class SMSReceiver extends BroadcastReceiver{
    private SharedPreferences sp;

    @Override
    public void onReceive(Context context, Intent intent) {
        Object[] objs = (Object[]) intent.getExtras().get("pdus");
        sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);

        for (Object b : objs) {
            SmsMessage sms =SmsMessage.createFromPdu((byte[]) b);
            String sender = sms.getOriginatingAddress();
            String phone = sp.getString("safenumber", "");
            String body = sms.getMessageBody();
            if (sender.contains(phone)) {
                switch (body) {
                    case "#*location*#":
                        Intent i = new Intent(context, GPSService.class);
                        context.startService(i);
                        SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
                        String lastlocation = sp.getString("lastlocation", null);
                        if(TextUtils.isEmpty(lastlocation)) {
                            SmsManager.getDefault().sendTextMessage(sender, null, "getting location...", null, null);
                        } else {
                            SmsManager.getDefault().sendTextMessage(sender, null, lastlocation, null, null);
                        }

                        abortBroadcast();
                        break;
                    case "#*alarm*#":
                        MediaPlayer player = MediaPlayer.create(context, R.raw.aa);
                        player.setLooping(false);
                        player.start();
                        abortBroadcast();
                        break;
                    case "#*wipedata*#":
                        abortBroadcast();
                        break;
                    case "#*lockscreen*#":
                        abortBroadcast();
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
